import 'dart:convert';
import 'package:request_ruoyi/router/router.dart';
import '../../req/login_req.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:request_ruoyi/store/user_info.dart';

class Login extends HookWidget {
  const Login({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(title: const Text('登录')),
        body: Center(
          child: SingleChildScrollView(
            // 键盘弹出时防止溢出
            padding: const EdgeInsets.all(24),
            child: _LoginForm(), // 抽成独立 Widget，代码更干净
          ),
        ),
      ),
    );
  }
}

class _LoginForm extends HookWidget {
  const _LoginForm();

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    // final height = MediaQuery.of(context).size.height;
    final formKey = useMemoized(GlobalKey<FormState>.new); //表单key
    final usernameCtrl = useTextEditingController(); //用户名输入框
    final pwdCtrl = useTextEditingController(); //密码输入框
    final captchaCtrl = useTextEditingController(); //验证码输入框
    final captchaImgUrl = useState<String?>(null); //验证码图片
    final loading = useState(false); //加载状态
    final formContain = useState<Map<String, dynamic>>({
      'username': null,
      'password': null,
      'code': null,
      'uuid': null,
    }); // 表单数据

    Future<void> formVoluation({Map<String, dynamic>? res}) async {
      formContain.value = {
        ...formContain.value,
        'username': usernameCtrl.text.isEmpty ? '' : usernameCtrl.text, // 取文本
        'password': pwdCtrl.text.isEmpty ? '' : pwdCtrl.text,
        'code': captchaCtrl.text.isEmpty ? '' : captchaCtrl.text, // 验证码输入框文本
        'uuid': res?['uuid'] ?? formContain.value['uuid'], // 从验证码响应中获取 uuid
      };
    }

    Future<void> formClear() async {
      formContain.value = {
        'username': '',
        'password': '',
        'code': '',
        'uuid': '',
      };
    }

    // 获取验证码图片
    Future<void> getCode() async {
      loading.value = true;
      try {
        final res = await LoginReq.getCodeImg(); //获取验证码图片
        await formVoluation(res: res); // 更新表单数据
        captchaImgUrl.value = res['img'];
        debugPrint(
          'msg:${res['msg']} \n code:${res['code']} \n uuid: ${res['uuid']}',
        );
        debugPrint(formContain.value.toString());
      } finally {
        loading.value = false;
      }
    }

    // 页面加载时获取验证码图片
    useEffect(() {
      debugPrint("获取验证码图片");
      getCode(); // 页面加载时获取验证码图片
      debugPrint("获取验证码图片完成");
      return null; // 清理函数，这里不需要
    }, []);

    Future<void> login() async {
      await formVoluation();
      debugPrint("开始登录");
      final res = await LoginReq.login(formContain.value);
      if (!context.mounted) return;
      if (res['code'] == 200) {
        debugPrint("登录成功");
        debugPrint("Token: ${res['token']}");
        UserInfo().token = res['token'];
        UserInfo().userId = res['userId'];
        UserInfo().nickname = res['nickname'];
        debugPrint("用户信息: ${jsonEncode(UserInfo().token)}");
        formClear();
        const HomeRoute().go(context);
      } else {
        debugPrint("登录失败");
        debugPrint(res['msg']);
      }
    }

    return Form(
      key: formKey,
      child: Center(
        child: Column(
          children: [
            TextFormField(
              controller: usernameCtrl,
              keyboardType: TextInputType.text, // 设置键盘类型
              decoration: const InputDecoration(
                // 输入框装饰
                labelText: '用户名',
                prefixIcon: Icon(Icons.person),
                border: OutlineInputBorder(), // 边框样式
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入用户名';
                }
                return null;
              },
            ),
            SizedBox(height: 20),

            TextFormField(
              controller: pwdCtrl,
              keyboardType: TextInputType.visiblePassword,
              decoration: const InputDecoration(
                labelText: '密码',
                prefixIcon: Icon(Icons.lock),
                border: OutlineInputBorder(),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入密码';
                }
                return null;
              },
            ),

            SizedBox(height: 20),
            Row(
              children: [
                //验证码输入框
                ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: width * 0.5,
                  ), // 限制验证码输入框宽度
                  child: TextFormField(
                    controller: captchaCtrl,
                    keyboardType: TextInputType.number,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      prefixIcon: Icon(Icons.safety_check),
                      border: OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入验证码';
                      }
                      return null;
                    },
                  ),
                ),
                SizedBox(width: width * 0.05),
                //验证码图片
                GestureDetector(
                  onTap: getCode,
                  child: Container(
                    width: width * 0.35,
                    height: 48,
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: const Color.fromARGB(255, 107, 107, 107),
                      ),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: captchaImgUrl.value == null
                        ? const Icon(Icons.refresh, size: 24)
                        : Image.memory(
                            base64Decode(captchaImgUrl.value!),
                            fit: BoxFit.fill,
                          ),
                  ),
                ),
              ],
            ),

            SizedBox(
              width: double.infinity, // 按钮宽度填满父容器
              child: Padding(
                padding: const EdgeInsets.only(top: 50.0),
                child: ElevatedButton(
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      login(); // 调用登录方法
                    }
                  },
                  child: const Text('登录'),
                ),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                const LoginPhoneNumberRoute().go(context);
              },
              child: Text('手机验证码登录'),
            ),
          ],
        ),
      ),
    );
  }
}
